<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="queryParams.title" placeholder="请输入标题" clearable size="small"/>
          </el-form-item>
          <el-form-item label="动态类型" prop="dictTypeId">
            <el-select v-model="queryParams.dictCode"
                       clearable
                       size="small"
            >
              <el-option v-for="dictData in movementTypeOptions"
                         :key="dictData.dictCode"
                         :label="dictData.dictLabel"
                         :value="dictData.dictCode"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['content:movement:query']"
            >搜索
            </el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['content:movement:add']"
            >新增
            </el-button>
            <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['content:movement:export']"
                       @click="handleExport"
            >导出
            </el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="movementList" border @sort-change="handleSort"
                  :default-sort="{prop:'createTime',order:'descending'}"
        >
          <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true"/>
          <el-table-column label="内容" align="center" prop="content" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column label="图片" align="center" prop="iconUrl">
            <template slot-scope="scope">
              <template>
                <el-popover
                  placement="right"
                  trigger="hover"
                >
                  <img :src="scope.row.iconUrl" style="width: 300px"/>
                  <img slot="reference" :src="scope.row.iconUrl" style="width: 25px;height: 25px">
                </el-popover>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="动态类型" align="center" prop="dictLabel">
            <template slot-scope="scope">
              <template v-if="scope.row.dictLabel==='图片'">
                <el-tag>{{ scope.row.dictLabel }}</el-tag>
              </template>
              <template v-else>
                <el-tag type="success">{{ scope.row.dictLabel }}</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="跳转链接" align="center" prop="redirectUrl" :show-overflow-tooltip="true"/>
          <el-table-column label="点击量" align="center" prop="clickCount" width="100"/>
          <el-table-column label="发布状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                active-value="0"
                inactive-value="1"
                @change="statusSwitchChange($event,scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="组织名称" align="center" prop="deptName" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="center" prop="createTime" min-width="150" :show-overflow-tooltip="true"
                           sortable="custom"
          />
          <el-table-column label="操作" align="center" width="130">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-hasPermi="['content:movement:edit']"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                v-hasPermi="['content:movement:remove']"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改企业动态对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属组织" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true"
                          placeholder="请选择归属组织" :flat="true"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="动态类型" prop="dictCode">
              <el-select v-model="form.dictCode"
                         size="small"
                         @change="selectTypeChanged"
              >
                <el-option v-for="dictData in movementTypeOptions"
                           :key="dictData.dictCode"
                           :label="dictData.dictLabel"
                           :value="dictData.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="动态图片" prop="iconUrl">
              <el-row>
                <el-col :span="4">
                  <el-upload
                    ref="iconUpload"
                    accept=".jpg, .png"
                    :headers="upload.headers"
                    :action="upload.url"
                    :data="{categoryId: form.categoryId}"
                    :on-change="iconImgChange"
                    :disabled="upload.isIconImgUploading"
                    :on-progress="handleIconImgUploadProgress"
                    :on-success="handleIconImgSuccess"
                    :auto-upload="false"
                    :show-file-list="false"
                    list-type="picture"
                  >
                    <el-button size="small" style="margin-top: 5px;margin-bottom: 5px">选择图片</el-button>
                  </el-upload>
                </el-col>
                <el-col :span="4">
                <span style="width: 50px;height: 50px;">
                <img :src="imageUrl" v-if="imageUrl" style="width: 50px;height: 50px">
              </span>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="动态标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="动态内容" prop="content">
              <el-row>
                <template>
                  <el-input type="textarea" :rows="4" v-model="form.content" placeholder="请输入内容"/>
                </template>
              </el-row>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="跳转链接" prop="redirectUrl">
              <el-input v-model="form.redirectUrl" placeholder="请输入点击后跳转链接"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="发布状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="item in statusOptions"
                  :key="item.dictValue"
                  :label="item.dictValue"
                >{{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptTreeSelect } from '@/api/system/dept'
import {
  addMovement,
  delMovement,
  exportMovement,
  listMovement,
  updateMovement,
  updateMovementStatus
} from '@/api/system/movement'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getToken } from '@/utils/auth'

export default {
  name: 'index',
  components: { Treeselect },
  data() {
    return {
      movementList: [],
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 用户表格数据
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 当前选择的组织
      selectedOrgCode: '',
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 状态数据字典
      statusOptions: [{ dictValue: '0', dictLabel: '发布' }, { dictValue: '1', dictLabel: '未发布' }],
      // 是否为轮播图
      swiperOptions: [{ value: '0', label: '是' }, { value: '1', label: '否' }],
      // 企业动态数据字典
      movementTypeOptions: [],
      // 表单参数
      form: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictCode: undefined,
        title: undefined,
        content: undefined,
        clickCount: undefined,
        deptId: undefined,
        status: undefined,
        orgCode: undefined,
        orderByCreateTime: 'desc'
      },
      // 是否为图片动态
      selectPicture: true,
      // 图片是否已被修改
      imageChanged: false,
      // 修改时企业动态的图片
      preImgUrl: null,
      imageUrl: null,
      // 图片对象
      imageObject: null,
      // 动态图片是否已上传完成
      imageUploadCompleted: false,
      // 图片上传参数
      upload: {
        // 弹出层标题（用户导入）
        // 是否禁用图标上传
        isIconImgUploading: false,
        // 是否禁用动态图片上传
        isMovementImgUploading: false,
        // 是否更新已经存在的用户数据
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/image/uploadMovementImage'
      },
      rules: {
        dictCode: [
          { required: true, message: '动态类型不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '所属组织不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDictDataByType('sys_movement').then(response => {
      this.movementTypeOptions = response.data
    })
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    },

    imageUploadCompleted(value) {
      if (value) {
        this.submitData()
      }
    }
  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        // 顶层组织不可选
        if (this.deptOptions[0].id === 100) {
          this.deptOptions[0].isDisabled = true
        }
      })
    },
    /** 查询企业动态列表 */
    getList() {
      this.loading = true
      if (!this.queryParams.deptId) {
        // 取出当前用户的组织ID
        this.queryParams.deptId = this.$store.getters.deptId
      }
      listMovement(this.queryParams).then(response => {
        this.movementList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dictCode: undefined,
        title: undefined,
        content: undefined,
        iconUrl: undefined,
        redirectUrl: undefined,
        deptId: undefined,
        remark: undefined,
        orderNum: undefined,
        status: '1',
        swiper: '1'
      }
      this.resetForm('form')
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.imageUrl = null

      // 顶层组织不可选
      if (this.selectedOrgCode === '' || this.selectedOrgCode === 100) {
        this.selectedOrgCode = null
      }

      this.reset()
      // 设置默认类型为图片
      let dictData = this.movementTypeOptions.find(item => {
        return item.dictValue === 'pictureOnly'
      })
      if (dictData) {
        this.form.dictCode = dictData.dictCode
      }

      this.form.deptId = this.selectedOrgCode
      this.open = true
      this.title = '添加企业动态'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = JSON.parse(JSON.stringify(row))

      let dictData = this.movementTypeOptions.find(item => {
        return item.dictCode === row.dictCode
      })
      if (dictData) {
        this.selectPicture = dictData.dictValue === 'pictureOnly'
      } else {
        this.selectPicture = false
      }

      this.preImgUrl = this.form.iconUrl
      this.imageUrl = this.form.iconUrl

      this.open = true
      this.title = '修改企业动态'
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 若是图片动态
          if (this.selectPicture) {
            // 若图片已修改
            if (this.imageChanged) {
              this.$refs.iconUpload.submit()
            } else {
              // 图片未修改时直接将其标记为上传完成
              this.imageUploadCompleted = true
            }
          } else {
            // 若图片已修改
            if (this.imageChanged) {
              this.$refs.iconUpload.submit()
            } else {
              // 图片未修改时直接将其标记为上传完成
              this.imageUploadCompleted = true
            }
          }
        }
      })
    },

    // 提交数据, 新增或修改企业动态数据库
    submitData() {
      // 获取图片链接
      if (this.imageChanged && this.imageObject) {
        this.form.iconUrl = this.imageObject.url
      }

      if (this.form.id !== undefined) {
        updateMovement(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess('修改成功')
            this.getList()
          }
        })
      } else {
        addMovement(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess('新增成功')
            this.getList()
          }
        })
      }

      // 重置相关状态
      this.open = false
      this.selectPicture = null
      this.imageChanged = false
      this.imageUploadCompleted = false
      this.imageObject = null
    },

    // 所选动态类型发生改变
    selectTypeChanged(data) {
      this.imageChanged = false
      // this.imageUrl = null

      let dictData = this.movementTypeOptions.find(item => {
        return item.dictCode === data
      })
      if (dictData) {
        this.selectPicture = dictData.dictValue === 'pictureOnly'
      } else {
        this.selectPicture = false
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delMovement({ id: row.id })
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.selectedOrgCode = data.id
      this.handleQuery()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 图标文件修改
    iconImgChange(file, fileList) {
      // 当有文件是取该文件名, 因为on-change在文件上传成功后也会调用, 此时fileList的长度为0, 且不需要再取文件名了
      this.imageUrl = file.url
      this.imageChanged = true

      // 只保留最新的文件
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },

    // 图标上传中处理
    handleIconImgUploadProgress(event, file, fileList) {
      this.upload.isIconImgUploading = true
    },

    // 图标上传成功处理
    handleIconImgSuccess(response, file, fileList) {
      this.imageObject = response.data
      this.$refs.iconUpload.clearFiles()
      this.upload.isIconImgUploading = false
      this.imageUploadCompleted = true
    },

    // 动态图片修改
    movementImgChange(file, fileList) {
      // 当有文件是取该文件名, 因为on-change在文件上传成功后也会调用, 此时fileList的长度为0, 且不需要再取文件名了
      this.imageUrl = file.url
      this.imageChanged = true

      // 只保留最新的文件
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },

    // 动态图片上传中处理
    handleMovementImgUploadProgress(event, file, fileList) {
      this.upload.isMovementImgUploading = true
    },

    // 动态图片上传成功处理
    handleMovementImgSuccess(response, file, fileList) {
      this.imageObject = response.data
      this.$refs.movementImgUpload.clearFiles()
      this.upload.isMovementImgUploading = false
      this.imageUploadCompleted = true
    },

    statusSwitchChange(value, data) {
      this.$confirm('是否确认发布?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateMovementStatus({
          id: data.id,
          deptId: data.deptId,
          dictCode: data.dictCode,
          status: data.status,
          iconUrl: data.iconUrl
        }).then(response => {
          this.getList()
          this.msgSuccess('修改成功')
        }, reject => {
          // 若请求失败, 如没有权限
          this.getList()
        })
      }).catch(() => {
        this.getList()
        this.msgInfo('修改取消')
      })
    },
    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportMovement(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },

    /**
     * 点击排序按钮
     * @param event
     */
    handleSort(event) {
      //先清空之前的排序
      this.queryParams.orderByCreateTime = undefined

      // 转换排序的字符串, 将其转为sql中的形式
      let orderType = null
      if (event.order) {
        orderType = event.order === 'ascending' ? 'asc' : 'desc'
      }

      this.queryParams.orderByCreateTime = orderType

      this.getList()
    }
  }
}
</script>

<style scoped>

</style>
